<?php
namespace Modules\Payment\Entities;

use Yansongda\Pay\Pay;
use Modules\Payment\Entities\PaymentRecord;

use ThrowException;
use Miniapp;
use Cache;

class AliPay
{
	protected $clientName;
	protected $payType;
	protected $pay;

	public function __construct($clientName, $payType)
	{
		$config = config('pay.alipay.' . $payType);

		// \Log::error($config);

		// if ($clientName)
		// 	$key = $clientName . '_' . $payType;
		// else 
		// 	$key = array_keys($config)[0];

		// $config = $config[];

		$this->pay = Pay::alipay($config);
		$this->payType = $payType;
		$this->clientName = $clientName;
	}

	public function __call($name, $arguments)
    {
    	return call_user_func_array(array($this->pay, $name), $arguments);
    }

	public function config($user, $order)
	{
		$money = $order->payPrice();
		$title = $order->title();
		$number = $order->payNumber();

		// 截取限定长度标题  
		$title = mb_substr($title, 0, 30);

        // for test
        // $money = 1;

		// $order = [
		// 	'out_trade_no' => $number,
		// 	'subject' => $title,
		// 	'total_amount' => $money,
		// ];

		// $wechatPayOrder = [
		//     'out_trade_no' => time(),
		//     'description' => 'subject-测试',
		//     'amount' => [
		//         'total' => '1',
		//     ],
		// ];

		try {
			switch ($this->payType) {

	            case 'app': 
	            	// app支付宝支付
					$order = [
						'out_trade_no' => $number,
						'subject' => $title,
						'total_amount' => $money / 100,
					];
	                $config = $this->pay->app($order)->getContent();
	                break;

	            case 'miniapp': 
	            	// 小程序支付
					$order = [
						'out_trade_no' => $number,
						'subject' => $title,
						'total_amount' => $money / 100,
						'buyer_id' => $user->getOpenidAtAlipay('miniapp')
					];
	            	$config = $this->pay->mini($order);
	            	break;
	            	
	            default:
	                break;
	        }
        }
		catch(\Yansongda\Pay\Exceptions\GatewayException $e) {
			$err  = $e->getMessage();
			\Log::error('获取支付宝支付配置失败: ' . $err);
			
			ThrowException::Conflict($err);
		}

        return $config;
	}

	public function refundMoney($order, $refundMoney = null, $options = []) 
	{
		// $payment = $order->payment() ?: ThrowException::Conflict('订单无支付记录');

		// \Log::error($payment);
		// exit();

		$orderType = 'single_order';

		$remark = @v($options['remark'], '订单退款');

		// $paymentRecord = $order->payment();
		$number = $order->pay_number;

		// \Log::error($number);
		// exit();

		$info = [
			'out_trade_no' => $number,
			'out_refund_no' => time(),
			'total_fee' => $order->pay_money_price,
			'refund_fee' => $refundMoney,
			'refund_desc' => $remark,
		];

		try {
			$res = $this->pay->refund($info);
		}
		catch(\Yansongda\Pay\Exceptions\GatewayException $e) {
			$err = $e->getMessage();
			\Log::error('订单: ' . $order->id . ' 退款失败:' . $err);
			ThrowException::Conflict('退款失败:' .  $err);
		}
	}


	public function recordPayment($order, $clientName, $paySubType, $data, $options = [])
	{
		$info = [
			'trade_number' => $data->trade_no,
			'out_trade_number' => $data->out_trade_no,
			'client_name' => $clientName,
			'pay_type' => 'alipay',
			'pay_sub_type' => $paySubType,
			'paid_at' => $data->gmt_create,
			'money' => intVal($data->total_amount) * 100,
			'status' => 2,
			'options' => $data
		];

		if ($order->number[0] == 'U') 
			$info['union_order_id'] = $order->id;
		else
			$info['order_id'] = $order->id;

		$record = PaymentRecord::create($info);

		$record->save();
	}
}
